package com.heisenhub.uua.service.login;


import com.heisenhub.common.oauth.entity.UuaUser;
import com.heisenhub.uua.service.AbstractCustomTokenGranter;
import com.heisenhub.uua.service.impl.UuaUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

@Slf4j
public class WebPcLoginGranter extends AbstractCustomTokenGranter {
    private UserDetailsService userService;
    private AuthenticationManager authenticationManager;

    private static final String USERNAME = "username";

    private static final String PASSWORD = "password";

    public WebPcLoginGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory , UserDetailsService userService, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, PASSWORD);
        this.userService = userService;
        this.authenticationManager=authenticationManager;
    }

    @Override
    protected UserDetails userLogin(Map<String, String> parameters) {
       // String grantType = parameters.get("grant_type");
        String username = parameters.get(USERNAME);
       String password = parameters.get(PASSWORD);
//
//        UserDetails userDetails = (UuaUser )userService.loadUserByUsername(username);
//
        Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        userAuth = authenticationManager.authenticate(userAuth);
        return (UuaUser) userAuth.getPrincipal();


       // return userService.loadUserByUsername(username);
    }
}
